import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
  Card,
  Tabs,
  Tag,
  Button,
  message,
  Spin,
  Row,
  Col,
  Divider
} from 'antd';
import {
  CopyOutlined,
  EditOutlined
} from '@ant-design/icons';
import { getCardDetails, getHolderDetails } from '@/api/modules/card';

const { TabPane } = Tabs;

/**
 * CVV信息接口定义
 * CVV是信用卡安全码，用于验证卡片真实性
 */
interface CvvInfo {
  cardId: string;           // 卡片ID
  cardNo: string;           // 卡号
  cvv: string;              // CVV安全码
  expirationDate: string;   // 过期日期
}

/**
 * 卡片详情接口定义
 * 包含卡片的所有详细信息
 */
interface CardDetail {
  matrixAccount: string;              // 矩阵账户
  cardId: string;                     // 卡片ID
  cardNo: string;                     // 卡号
  memberId: string;                   // 会员ID
  cardType: string;                   // 卡片类型
  cardScheme: string;                 // 卡组织
  cardCurrency: string;               // 卡片货币
  firstName: string;                  // 名字
  lastName: string;                   // 姓氏
  nationality: string;                // 国籍
  email: string;                      // 邮箱
  mobilePrefix: string;               // 手机前缀
  mobile: string;                     // 手机号
  transactionLimitType: string;       // 交易限制类型
  cardBalance: number;                // 卡片余额
  expirationDate: string;             // 过期日期
  cardStatus: string;                 // 卡片状态
  billingCountry: string;             // 账单国家
  billingState: string;               // 账单州/省
  billingCity: string;                // 账单城市
  billingAddress: string;             // 账单地址
  billingPostalCode: string;          // 账单邮编
  billingAddressUpdatable: string;    // 账单地址是否可更新
  maskCardNo: string;                 // 掩码卡号
  nickname: string;                   // 昵称
  createdAt: string;                  // 创建时间
  cardFormFactor: string;             // 卡片形式（实体/虚拟）
  cardholderId: string;               // 持卡人ID
  cardholderNameAbbreviation: string; // 持卡人姓名缩写
  recipientId: string;                // 接收者ID
  updateAt: string;                   // 更新时间
}

/**
 * 持卡人详情接口定义
 * 包含持卡人的个人信息
 */
interface CardHolderDetails {
  cardholderId: string;               // 持卡人ID
  nationalityCountryCode: string;     // 国籍代码
  cardholderNameAbbreviation: string; // 持卡人姓名缩写
  firstName: string;                  // 名字
  lastName: string;                   // 姓氏
  firstNameAbbr: string;              // 名字缩写
  lastNameAbbr: string;               // 姓氏缩写
  email: string;                      // 邮箱
  mobilePrefix: string;               // 手机前缀
  mobile: string;                     // 手机号
  dateOfBirth: string;                // 出生日期
  residentialCountryCode: string;     // 居住国家代码
  residentialAddress: string;         // 居住地址
  residentialCity: string;            // 居住城市
  residentialPostalCode: string;      // 居住邮编
  residentialState: string;           // 居住州/省
}

/**
 * 卡片详情响应接口
 * API返回的卡片详情数据结构
 */
interface CardDetailResponse {
  status: number;  // 状态码
  data: {
    cardholderId: number;  // 持卡人ID
    cvvInfo: CvvInfo;      // CVV信息
    cardDetail: CardDetail; // 卡片详情
  };
  msg: string;     // 消息
}

/**
 * 持卡人详情响应接口
 * API返回的持卡人详情数据结构
 */
interface HolderDetailResponse {
  status: number;  // 状态码
  data: {
    cardholder_json: CardHolderDetails; // 持卡人JSON数据
  };
  msg: string;     // 消息
}

/**
 * 卡片详情组件
 * 展示单个卡片的详细信息，包括卡片数据和持卡人信息
 */
const CardDetail: React.FC = () => {
  const [searchParams] = useSearchParams(); // 获取URL查询参数
  const cardId = searchParams.get('id'); // 从URL获取卡片ID
  const [loading, setLoading] = useState(true); // 加载状态
  const [cardDetail, setCardDetail] = useState<CardDetail | null>(null); // 卡片详情数据
  const [cvvInfo, setCvvInfo] = useState<CvvInfo | null>(null); // CVV信息
  const [cardholderDetails, setCardholderDetails] = useState<CardHolderDetails | null>(null); // 持卡人详情
  const [activeTab, setActiveTab] = useState('financial_details'); // 激活的标签页

  /**
   * 获取卡片详情
   * 从API获取卡片详细信息和持卡人信息
   */
  const fetchCardDetails = async () => {
    if (!cardId) return; // 如果没有卡片ID，直接返回

    setLoading(true); // 开始加载
    try {
      // 调用API获取卡片详情
      const response = await getCardDetails({ id: parseInt(cardId) });
      const data = response.data as unknown as CardDetailResponse; // 类型转换
      
      if (data.status === 0) {
        setCardDetail(data.data.cardDetail); // 设置卡片详情
        setCvvInfo(data.data.cvvInfo); // 设置CVV信息

        // 获取持卡人详情
        const holderResponse = await getHolderDetails({ id: data.data.cardholderId });
        const holderData = holderResponse.data as unknown as HolderDetailResponse; // 类型转换
        
        if (holderData.status === 0) {
          setCardholderDetails(holderData.data.cardholder_json); // 设置持卡人详情
        } else {
          message.error(holderData.msg); // 显示错误消息
        }
      } else {
        message.error(data.msg); // 显示错误消息
      }
    } catch (error) {
      console.error('获取卡片详情失败:', error);
      message.error('获取卡片详情失败');
    } finally {
      setLoading(false); // 结束加载
    }
  };

  /**
   * 复制文本到剪贴板
   * @param text 要复制的文本
   */
  const copyText = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('复制成功');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  /**
   * 格式化卡号（每4位加空格）
   * @param cardNo 原始卡号
   * @returns 格式化后的卡号
   */
  const formatCardNumber = (cardNo: string) => {
    const cleaned = cardNo.replace(/\D/g, ''); // 移除非数字字符
    return cleaned.replace(/(\d{4})(?=\d)/g, '$1 '); // 每4位数字加空格
  };

  // useEffect钩子：当卡片ID变化时重新获取详情
  useEffect(() => {
    fetchCardDetails();
  }, [cardId]);

  // 加载状态显示
  if (loading) {
    return (
      <div className="p-6">
        <Card>
          <div style={{ textAlign: 'center', padding: '50px' }}>
            <Spin size="large" /> {/* 大型加载旋转图标 */}
            <div style={{ marginTop: 16 }}>加载中...</div>
          </div>
        </Card>
      </div>
    );
  }

  // 数据加载失败显示
  if (!cardDetail || !cvvInfo) {
    return (
      <div className="p-6">
        <Card>
          <div style={{ textAlign: 'center', padding: '50px' }}>
            <p>卡片不存在或加载失败</p>
            <Button type="primary" onClick={fetchCardDetails}>
              重试
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6">
      <Card className="m-0 px-6 shadow-[0px_0px_16px_0px_rgba(0,0,0,0.03)]">
        <Row gutter={40}>
          {/* 左侧：卡片信息 */}
          <Col xl={12} lg={12} md={24} sm={24} xs={24}>
            <div>
              <span className="align-middle text-2xl font-bold text-accent-foreground">卡片详情</span>
              <span className="ml-2 inline-block align-middle text-sm text-gray-500">卡ID </span>
              <span className="ml-2 inline-block align-middle text-sm">{cardDetail.cardId} </span>
            </div>
            <Row gutter={40} className="mt-4">
              {/* 卡片图像区域 */}
              <Col xl={11} lg={11} md={24} sm={24} xs={24}>
                <div
                  className="card_img aspect-[1.5] flex flex-col justify-evenly px-3 bg-cover bg-no-repeat bg-center"
                  style={{
                    backgroundImage: cardDetail.cardStatus === 'normal'
                      ? "url('https://wallex2.oss-cn-hangzhou.aliyuncs.com/asset/images/card/normal_card.png')"
                      : "url('https://wallex2.oss-cn-hangzhou.aliyuncs.com/asset/images/card/other_cards.png')"
                  }}
                >
                  <p className="text-right">
                    <Tag color="success">
                      {cardDetail.cardFormFactor === 'virtual_card' ? '虚拟卡' : '实体卡'}
                    </Tag>
                  </p>
                  <div>
                    <p className="my-2 text-2xl font-bold">
                      {formatCardNumber(cardDetail.cardNo)} {/* 格式化显示卡号 */}
                    </p>
                    <p className="my-2 font-bold">
                      {cvvInfo.expirationDate} {/* 显示有效期 */}
                    </p>
                  </div>
                  <p className="text-right">
                    <img
                      src={`https://wallex2.oss-cn-hangzhou.aliyuncs.com/asset/images/card/${cardDetail.cardScheme}.png`}
                      alt={cardDetail.cardScheme}
                      className="h-6 w-10 align-end"
                    />
                  </p>
                </div>
              </Col>
              {/* 卡片详细信息 */}
              <Col xl={13} lg={13} md={24} sm={24} xs={24} className="text-sm">
                <p className="mb-4">
                  <span className="inline-block min-w-[35px] text-gray-500">卡号</span>
                  <span>
                    {cardDetail.cardNo}
                    <CopyOutlined
                      className="ml-1 size-4 cursor-pointer align-middle text-primary"
                      onClick={() => copyText(cardDetail.cardNo)} // 复制卡号
                    />
                  </span>
                </p>
                <p className="mb-4">
                  <span className="inline-block min-w-[35px] text-gray-500">卡本币</span>
                  <span>
                    <img
                      className="mr-2 inline-block w-5 rounded-full align-middle"
                      src={`https://wallex2.oss-cn-hangzhou.aliyuncs.com/asset/images/flags/${cardDetail.cardCurrency.toLowerCase()}.png`}
                      alt={cardDetail.cardCurrency}
                    />
                    <span className="inline-block px-1 align-middle">{cardDetail.cardCurrency}</span>
                  </span>
                </p>
                <p className="mb-4">
                  <span className="inline-block min-w-[35px] text-gray-500">卡余额</span>
                  <span className="inline-block align-middle font-bold">{cardDetail.cardBalance}</span>
                  <Button size="small" type="primary" className="ml-3">
                    转入
                  </Button>
                </p>
                <p className="mb-4">
                  <span className="inline-block min-w-[35px] text-gray-500">有效期</span>
                  <span>
                    {cvvInfo.expirationDate}
                    <CopyOutlined
                      className="ml-1 size-4 cursor-pointer align-text-top text-primary"
                      onClick={() => copyText(cvvInfo.expirationDate)} // 复制有效期
                    />
                  </span>
                </p>
                <p className="mb-4">
                  <span className="inline-block min-w-[35px] text-gray-500">CVV</span>
                  <span>
                    {cvvInfo.cvv}
                    <CopyOutlined
                      className="ml-1 size-4 cursor-pointer align-text-top text-primary"
                      onClick={() => copyText(cvvInfo.cvv)} // 复制CVV
                    />
                  </span>
                </p>
              </Col>
            </Row>
            <Divider className="mb-2 mt-4" />
            <Row gutter={40} className="text-sm">
              <Col xl={11} lg={11} md={24} sm={24} xs={24}>
                <p className="mb-4">
                  <span className="inline-block min-w-[30px] text-gray-500">创建时间</span>
                  <span className="inline-block align-middle">
                    {cardDetail.createdAt.replace('T', ' ')} {/* 格式化时间显示 */}
                  </span>
                </p>
                {cardDetail.cardStatus !== 'normal' && (
                  <p>
                    <span className="inline-block min-w-[30px] text-gray-500">销卡时间</span>
                  <span className="inline-block align-middle">
                    {cardDetail.updateAt.replace('T', ' ')} {/* 格式化时间显示 */}
                  </span>
                  </p>
                )}
              </Col>
              <Col xl={13} lg={13} md={24} sm={24} xs={24}>
                <p className="mb-4">
                  <span className="inline-block min-w-[30px] text-gray-500">昵称</span>
                  <span className="inline-block align-middle">
                    {cardDetail.nickname ? cardDetail.nickname : '-'}
                    <EditOutlined className="ml-3 size-4 cursor-pointer align-middle" />
                  </span>
                </p>
              </Col>
            </Row>
          </Col>
          {/* 右侧：持卡人信息 */}
          <Col xl={12} lg={12} md={24} sm={24} xs={24}>
            <div>
              <span className="align-middle text-2xl font-bold">持卡人信息</span>
              <span className="ml-2 inline-block align-middle text-sm text-gray-500">持卡人ID </span>
              <span className="ml-2 inline-block align-middle text-sm">{cardDetail.cardholderId} </span>
            </div>

            <Row gutter={20} className="mt-4">
              {/* 持卡人基本信息 */}
              <Col xl={12} lg={12} md={24} sm={24} xs={24}>
                <div className="min-h-[280px] rounded-lg bg-gray-100 bg-opacity-10 p-4 text-sm">
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">国籍</span>
                    <span>
                      <img
                        className="mr-2 inline-block w-6 rounded-full align-middle"
                        src={`https://wallex2.oss-cn-hangzhou.aliyuncs.com/asset/images/flags/${cardDetail.nationality.toLowerCase()}.png`}
                        alt={cardDetail.nationality}
                      />
                      <span className="align-middle">{cardDetail.nationality}</span>
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">姓名</span>
                    <span>
                      {cardDetail.firstName} {cardDetail.lastName}
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">姓名缩写</span>
                    <span>
                      {cardholderDetails?.cardholderNameAbbreviation || '-'}
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">邮箱</span>
                    <span>
                      {cardDetail.email}
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">手机号</span>
                    <span>
                      {cardDetail.mobilePrefix}-{cardDetail.mobile}
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">出生日期</span>
                    <span>
                      {cardholderDetails?.dateOfBirth || '-'}
                    </span>
                  </p>
                </div>
              </Col>
              {/* 账单地址信息 */}
              <Col xl={12} lg={12} md={24} sm={24} xs={24}>
                <div className="min-h-[280px] rounded-lg bg-gray-100 bg-opacity-10 p-4 text-sm">
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">账单国家</span>
                    <span>
                      <img
                        className="mr-2 inline-block w-6 rounded-full align-middle"
                        src={`https://wallex2.oss-cn-hangzhou.aliyuncs.com/asset/images/flags/${cardDetail.billingCountry.toLowerCase()}.png`}
                        alt={cardDetail.billingCountry}
                      />
                      <span className="align-middle">{cardDetail.billingCountry}</span>
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">州/城市</span>
                    <span>
                      {cardDetail.billingState} {cardDetail.billingCity}
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">详细地址</span>
                    <span className="inline-block">
                      {cardDetail.billingAddress}
                    </span>
                  </p>
                  <p className="mb-4">
                    <span className="inline-block min-w-[30px] text-gray-500">邮编</span>
                    <span>
                      {cardDetail.billingPostalCode}
                    </span>
                  </p>
                  <p className="mb-4">
                    <Button type="default" icon={<EditOutlined />}>
                      更新账单地址
                    </Button>
                  </p>
                </div>
              </Col>
            </Row>
          </Col>
        </Row>
      </Card>

      {/* 标签页：资金明细和卡历史 */}
      <Tabs activeKey={activeTab} onChange={setActiveTab} className="mt-5">
        <TabPane tab="资金明细" key="financial_details">
          {/* 资金明细表格组件将在这里 */}
          <div className="text-center py-8 text-gray-400">
            资金明细功能开发中...
          </div>
        </TabPane>
        <TabPane tab="卡历史" key="card_history">
          {/* 卡历史表格组件将在这里 */}
          <div className="text-center py-8 text-gray-400">
            卡历史功能开发中...
          </div>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default CardDetail;